package com.jm.offer.easy;

import com.jm.offer.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * @Description https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
 * @date 2022/4/23 8:02
 */
public class _52两个链表的第一个公共节点 {

    public static void main(String[] args) {
        ListNode headA = new ListNode(4,new ListNode(1,new ListNode(8,new ListNode(4,new ListNode(5)))));
        ListNode headB = new ListNode(5,new ListNode(0,new ListNode(1,new ListNode(8,new ListNode(4,new ListNode(5))))));
        System.out.println(getIntersectionNode(headA, headB).val);
    }

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> visited = new HashSet<ListNode>();
        ListNode temp = headA;
        while (temp != null) {
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (temp != null) {
            if (visited.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }
}

